<template>
  <div class="layout">
    <AppHeader
      :is-logged-in="isLoggedIn"
      :username="username"
      @open-login="openLogin"
      @open-register="openRegister"
      @logout="handleLogout"
    />
    <main class="main">
      <RouterView v-slot="{ Component }">
        <component :is="Component" />
      </RouterView>
    </main>
    <footer class="footer">
      <div class="container footer__inner">
        <div>
          <h4>平台优势</h4>
          <p>多仓联动 · 原厂正品 · 审计可追溯 · 覆盖核实/下单/结算全链路</p>
        </div>
        <div>
          <h4>参考文档</h4>
          <ul>
            <li><code>server/docs/system_overview.md</code></li>
            <li><code>server/docs/cart_workflows.md</code></li>
            <li><code>server/docs/settlement_finance_plan.md</code></li>
            <li><code>server/docs/product_schema_analysis.md</code></li>
          </ul>
        </div>
        <div>
          <h4>联系我们</h4>
          <p>运营热线：400-800-2025<br />商务合作：supply@bearingmall.com</p>
        </div>
      </div>
    </footer>
    <AuthModal
      :open="showLogin"
      :default-phone="loginDefaultPhone"
      @close="showLogin = false"
      @login="handleLogin"
    />
    <RegisterModal
      :open="showRegister"
      @close="showRegister = false"
      @registered="handleRegistered"
    />
    <PartialFlowDialog
      :result="partialResult"
      @close="partialResult = null"
      @confirm="handlePartialConfirm"
    />
  </div>
</template>

<script setup>
import { computed, provide, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import AppHeader from "./components/AppHeader.vue";
import AuthModal from "./components/AuthModal.vue";
import RegisterModal from "./components/RegisterModal.vue";
import PartialFlowDialog from "./components/PartialFlowDialog.vue";
import { useUserStore } from "./store/user";
import { useCartStore } from "./store/cart";
import { useVerificationStore } from "./store/verification";
import { message } from "./utils/message";

const router = useRouter();
const route = useRoute();

const userStore = useUserStore();
const cartStore = useCartStore();
const verificationStore = useVerificationStore();

const { isLoggedIn, username } = storeToRefs(userStore);

const showLogin = ref(false);
const showRegister = ref(false);
const loginDefaultPhone = ref("");
const partialResult = ref(null);

const openLogin = () => {
  showLogin.value = true;
};

const openRegister = () => {
  showRegister.value = true;
};

provide("appBridge", {
  openLogin,
  openRegister
});

const loadAfterLogin = async () => {
  await Promise.allSettled([
    cartStore.load(),
    verificationStore.load({ page: 1, page_size: 10 })
  ]);
};

const clearAfterLogout = () => {
  cartStore.clear();
  verificationStore.clear();
  loginDefaultPhone.value = "";
};

const handleLogin = async credentials => {
  try {
    const result = await userStore.signIn(credentials);
    showLogin.value = false;
    if (result?.partial) {
      partialResult.value = result;
      message.warning(result.message || "请继续完成后续流程");
      router.push({ name: "member" });
      return;
    }
    message.success("登录成功，已同步价格与企业数据。");
    loginDefaultPhone.value = "";
    await loadAfterLogin();

    const redirect = route.query.redirect;
    if (typeof redirect === "string" && redirect) {
      router.replace(redirect).catch(() => {});
    }
  } catch (error) {
    message.error(error.message || "登录失败");
  }
};

const handleLogout = async () => {
  await userStore.signOut();
  message.info("已退出登录，价格信息已隐藏。");
  clearAfterLogout();
  partialResult.value = null;
  router.push({ name: "home" });
};

const handlePartialConfirm = action => {
  partialResult.value = null;
  if (action === "need_bind_phone" || action === "need_verify_identity") {
    router.push({ name: "member" });
    if (action === "need_bind_phone") {
      message.info("请在会员中心绑定手机号后继续");
    } else {
      message.info("请在会员中心完善企业认证资料");
    }
  }
};

const handleRegistered = phone => {
  loginDefaultPhone.value = phone || "";
  showRegister.value = false;
  showLogin.value = true;
};

watch(isLoggedIn, value => {
  if (value) {
    partialResult.value = null;
    loadAfterLogin();
  } else {
    clearAfterLogout();
  }
});

watch(
  () => userStore.partial,
  value => {
    if (value?.partial) {
      partialResult.value = value;
    } else if (!isLoggedIn.value) {
      partialResult.value = null;
    }
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
.layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main {
  flex: 1;
  padding: 0 0 48px;
}

.footer {
  background: #0d1a2b;
  color: rgba(255, 255, 255, 0.85);
  padding: 36px 0;
}

.footer__inner {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 24px;

  h4 {
    margin: 0 0 10px;
  }

  p,
  ul {
    margin: 0;
    font-size: 14px;
    color: rgba(255, 255, 255, 0.7);
  }

  ul {
    padding-left: 18px;
    li + li {
      margin-top: 6px;
    }
  }
}
</style>
